<template>
  <div class="role-permission-tab">
    <!-- 角色选择 -->
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="header-actions">
            <el-tag type="info" size="small">
              共 {{ roleList.length }} 个角色
            </el-tag>
            <el-button type="primary" @click="handleAddRole">
              <el-icon><Plus /></el-icon> 添加角色
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="roleLoading"
        :data="roleList"
        style="width: 100%"
        border
        highlight-current-row
        @current-change="handleRoleChange"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色代码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="enable" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'" size="small">
              {{ row.enable ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag type="primary" size="small">
              {{ row.permissions?.length || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditRole(row)">
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteRole(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限分配 -->
    <el-card v-if="selectedRole" class="permission-card">
      <template #header>
        <div class="card-header">
          <span>{{ selectedRole.name }} - 权限分配</span>
          <div class="header-actions">
            <el-button 
              type="success" 
              @click="handleSavePermissions" 
              :loading="saving"
            >
              <el-icon><Check /></el-icon> 
              保存权限
            </el-button>
            <el-button @click="handleResetPermissions">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </div>
        </div>
      </template>

      <div class="permission-assignment">
        <!-- 超级管理员提示 -->
        <el-alert
          v-if="selectedRole?.code === 'SUPER_ADMIN'"
          title="超级管理员说明"
          type="info"
          :closable="false"
          show-icon
          class="admin-alert"
        >
          <template #default>
            <p>超级管理员（SUPER_ADMIN）默认拥有系统所有权限。</p>
            <p>建议为超级管理员分配所有权限，以确保权限检查功能正常工作。</p>
          </template>
        </el-alert>
        
        <!-- 权限类型标签 -->
        <el-tabs v-model="activePermissionTab" class="permission-tabs">
          <el-tab-pane label="菜单权限" name="menu">
            <div class="permission-tree-container">
              <el-tree
                ref="menuTreeRef"
                :data="menuPermissionTree"
                :props="treeProps"
                v-model:checked-keys="checkedMenuKeys"
                show-checkbox
                node-key="id"
                class="permission-tree"
                @check-change="handleMenuCheckChange"
              >
                <template #default="{ node, data }">
                  <div class="permission-node">
                    <el-icon v-if="data.icon" :size="16" class="node-icon">
                      <component :is="data.icon" />
                    </el-icon>
                    <span class="node-label">{{ data.name }}</span>
                    <el-tag v-if="data.path" type="info" size="small" class="path-tag">
                      {{ data.path }}
                    </el-tag>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-tab-pane>

          <el-tab-pane label="按钮权限" name="button">
            <div class="button-permissions">
              <el-table
                ref="buttonTableRef"
                :data="buttonPermissions"
                style="width: 100%"
                border
                v-loading="permissionLoading"
                :row-key="(row: Permission) => row.id"
                @selection-change="handleButtonSelectionChange"
              >
                <el-table-column 
                  type="selection" 
                  width="55"
                />
                <el-table-column prop="name" label="按钮名称" min-width="120" />
                <el-table-column prop="code" label="按钮代码" min-width="150" />
                <el-table-column prop="method" label="HTTP方法" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getMethodTagType(row.method)" size="small" v-if="row.method">
                      {{ row.method }}
                    </el-tag>
                    <span v-else style="color: var(--el-text-color-placeholder)">-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                <template #empty>
                  <el-empty description="暂无按钮权限数据" :image-size="100">
                    <template #description>
                      <p>系统中还没有配置按钮权限</p>
                      <p style="color: var(--el-text-color-secondary); font-size: 12px; margin-top: 8px;">
                        请在"权限列表"或"权限树"标签页中添加按钮类型的权限
                      </p>
                    </template>
                  </el-empty>
                </template>
              </el-table>
            </div>
          </el-tab-pane>

          <el-tab-pane label="API权限" name="api">
            <div class="api-permissions">
              <el-table
                ref="apiTableRef"
                :data="apiPermissions"
                style="width: 100%"
                border
                v-loading="permissionLoading"
                :row-key="(row: Permission) => row.id"
                @selection-change="handleApiSelectionChange"
              >
                <el-table-column 
                  type="selection" 
                  width="55"
                />
                <el-table-column prop="name" label="API名称" min-width="120" />
                <el-table-column prop="code" label="API代码" min-width="150" />
                <el-table-column prop="path" label="API路径" min-width="200" show-overflow-tooltip />
                <el-table-column prop="method" label="HTTP方法" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getMethodTagType(row.method)" size="small" v-if="row.method">
                      {{ row.method }}
                    </el-tag>
                    <span v-else style="color: var(--el-text-color-placeholder)">-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                <template #empty>
                  <el-empty description="暂无API权限数据" :image-size="100">
                    <template #description>
                      <p>系统中还没有配置API权限</p>
                      <p style="color: var(--el-text-color-secondary); font-size: 12px; margin-top: 8px;">
                        请在"权限列表"或"权限树"标签页中添加API类型的权限
                      </p>
                    </template>
                  </el-empty>
                </template>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 权限预览 -->
    <el-card v-if="selectedRole" class="preview-card">
      <template #header>
        <div class="card-header">
          <span>权限预览</span>
          <el-tag type="success" size="small">
            已选择 {{ selectedPermissionCount }} 个权限
          </el-tag>
        </div>
      </template>

      <div class="permission-preview">
        <el-collapse v-model="activePreviewCollapse">
          <el-collapse-item title="菜单权限" name="menu">
            <div class="preview-content">
              <el-tag
                v-for="permission in selectedMenuPermissions"
                :key="permission.id"
                type="primary"
                size="small"
                class="preview-tag"
              >
                {{ permission.name }}
              </el-tag>
              <el-empty v-if="selectedMenuPermissions.length === 0" description="未选择菜单权限" />
            </div>
          </el-collapse-item>

          <el-collapse-item title="按钮权限" name="button">
            <div class="preview-content">
              <el-tag
                v-for="permission in selectedButtonPermissions"
                :key="permission.id"
                type="success"
                size="small"
                class="preview-tag"
              >
                {{ permission.name }}
              </el-tag>
              <el-empty v-if="selectedButtonPermissions.length === 0" description="未选择按钮权限" />
            </div>
          </el-collapse-item>

          <el-collapse-item title="API权限" name="api">
            <div class="preview-content">
              <el-tag
                v-for="permission in selectedApiPermissions"
                :key="permission.id"
                type="warning"
                size="small"
                class="preview-tag"
              >
                {{ permission.name }}
              </el-tag>
              <el-empty v-if="selectedApiPermissions.length === 0" description="未选择API权限" />
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>

    <!-- 角色编辑对话框 -->
    <RoleEditDialog 
      v-model="roleDialogVisible"
      :role="currentRole"
      :is-edit="isRoleEdit"
      @success="handleRoleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { 
  Check,
  Refresh,
  Plus
} from '@element-plus/icons-vue'
import { ElMessage, ElTree, ElMessageBox } from 'element-plus'
import { permissionApi, Permission } from '../api/permission'
import { userApi, Role } from '../api/user'
import RoleEditDialog from './RoleEditDialog.vue'

// 树组件引用
const menuTreeRef = ref<InstanceType<typeof ElTree> | null>(null)
const buttonTableRef = ref<any>(null)
const apiTableRef = ref<any>(null)

// 加载状态
const roleLoading = ref(false)
const permissionLoading = ref(false)
const saving = ref(false)

// 角色列表
const roleList = ref<Role[]>([])

// 选中的角色
const selectedRole = ref<Role | null>(null)

// 权限数据
const menuPermissionTree = ref<Permission[]>([])
const buttonPermissions = ref<Permission[]>([])
const apiPermissions = ref<Permission[]>([])

// 选中的权限
const checkedMenuKeys = ref<number[]>([])
const checkedButtonKeys = ref<number[]>([])
const checkedApiKeys = ref<number[]>([])

// 当前权限标签页
const activePermissionTab = ref('menu')

// 预览折叠面板
const activePreviewCollapse = ref(['menu'])

// 角色编辑对话框相关
const roleDialogVisible = ref(false)
const isRoleEdit = ref(false)
const currentRole = ref<Role | null>(null)

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 计算属性
const selectedMenuPermissions = computed(() => {
  return getAllCheckedPermissions(menuPermissionTree.value, checkedMenuKeys.value)
})

const selectedButtonPermissions = computed(() => {
  return buttonPermissions.value.filter((p: Permission) => checkedButtonKeys.value.includes(p.id))
})

const selectedApiPermissions = computed(() => {
  return apiPermissions.value.filter((p: Permission) => checkedApiKeys.value.includes(p.id))
})

const selectedPermissionCount = computed(() => {
  return checkedMenuKeys.value.length + checkedButtonKeys.value.length + checkedApiKeys.value.length
})

// 获取所有选中的权限（包括子权限）
const getAllCheckedPermissions = (permissions: Permission[], checkedKeys: number[]): Permission[] => {
  let result: Permission[] = []
  
  permissions.forEach(permission => {
    if (checkedKeys.includes(permission.id)) {
      result.push(permission)
    }
    
    if (permission.children && permission.children.length > 0) {
      result = result.concat(getAllCheckedPermissions(permission.children, checkedKeys))
    }
  })
  
  return result
}

// 获取角色列表
const fetchRoleList = async () => {
  roleLoading.value = true
  try {
    const res = await userApi.getRoleList()
    if (res && res.code === 200) {
      roleList.value = res.data || []
    } else {
      ElMessage.error('获取角色列表失败')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    roleLoading.value = false
  }
}

// 获取权限数据
const fetchPermissionData = async () => {
  permissionLoading.value = true
  try {
    // 获取菜单权限树
    try {
      const menuRes = await permissionApi.getMenuTree()
      if (menuRes && menuRes.code === 200) {
        menuPermissionTree.value = menuRes.data || []
      } else {
        console.warn('获取菜单权限树失败:', menuRes?.message || '未知错误')
        ElMessage.warning('获取菜单权限树失败: ' + (menuRes?.message || '未知错误'))
        menuPermissionTree.value = []
      }
    } catch (menuError: any) {
      console.error('获取菜单权限树异常:', menuError)
      const errorMsg = menuError?.response?.data?.message || menuError?.message || '获取菜单权限树失败'
      ElMessage.warning(errorMsg)
      menuPermissionTree.value = []
    }

    // 获取所有权限（用于筛选按钮和API权限）
    // 传递大数值的 num 参数以获取所有权限
    try {
      const allRes = await permissionApi.getAllPermissions({ num: 10000 })
      if (allRes && allRes.code === 200) {
        // findAll 返回的数据结构：{ code: 200, data: { data: [...], totalCount, ... } }
        // 需要访问 allRes.data.data 获取实际的权限数组
        const allPermissions = (allRes.data?.data || allRes.data || []) as Permission[]
        buttonPermissions.value = allPermissions.filter((p: Permission) => p.type === 'BUTTON')
        apiPermissions.value = allPermissions.filter((p: Permission) => p.type === 'API')
      } else {
        console.warn('获取所有权限失败:', allRes?.message || '未知错误')
        ElMessage.warning('获取所有权限失败: ' + (allRes?.message || '未知错误'))
        buttonPermissions.value = []
        apiPermissions.value = []
      }
    } catch (allError: any) {
      console.error('获取所有权限异常:', allError)
      const errorMsg = allError?.response?.data?.message || allError?.message || '获取所有权限失败'
      // 如果是权限不足，给出更友好的提示
      if (allError?.response?.status === 403) {
        ElMessage.warning('权限不足，无法获取权限列表。请联系管理员分配"查看权限列表"权限')
      } else if (allError?.response?.status === 401) {
        ElMessage.warning('登录已过期，请重新登录')
      } else {
        ElMessage.warning(errorMsg)
      }
      buttonPermissions.value = []
      apiPermissions.value = []
    }
  } catch (error: any) {
    console.error('获取权限数据失败:', error)
    const errorMsg = error?.response?.data?.message || error?.message || '获取权限数据失败'
    ElMessage.error(errorMsg)
    // 确保所有数据都被重置为空数组
    menuPermissionTree.value = []
    buttonPermissions.value = []
    apiPermissions.value = []
  } finally {
    permissionLoading.value = false
  }
}

// 角色选择变化
const handleRoleChange = async (role: Role) => {
  selectedRole.value = role
  
  // 重置选中的权限
  checkedMenuKeys.value = []
  checkedButtonKeys.value = []
  checkedApiKeys.value = []
  
  // 清空表格选中状态
  await nextTick()
  if (buttonTableRef.value) {
    buttonTableRef.value.clearSelection()
  }
  if (apiTableRef.value) {
    apiTableRef.value.clearSelection()
  }
  
  // 如果是超级管理员，自动选中所有权限
  if (role.code === 'SUPER_ADMIN') {
    // 获取所有菜单权限ID
    const getAllMenuIds = (permissions: Permission[]): number[] => {
      let ids: number[] = []
      permissions.forEach(permission => {
        ids.push(permission.id)
        if (permission.children && permission.children.length > 0) {
          ids = ids.concat(getAllMenuIds(permission.children))
        }
      })
      return ids
    }
    
    checkedMenuKeys.value = getAllMenuIds(menuPermissionTree.value)
    checkedButtonKeys.value = buttonPermissions.value.map(p => p.id)
    checkedApiKeys.value = apiPermissions.value.map(p => p.id)
    
    // 设置表格选中状态
    await nextTick()
    if (buttonTableRef.value) {
      buttonPermissions.value.forEach((permission: Permission) => {
        buttonTableRef.value.toggleRowSelection(permission, true)
      })
    }
    if (apiTableRef.value) {
      apiPermissions.value.forEach((permission: Permission) => {
        apiTableRef.value.toggleRowSelection(permission, true)
      })
    }
  } else {
    // 获取角色的实际权限
    try {
      const res = await userApi.getRolePermissions(role.id)
      if (res && res.code === 200 && res.data) {
        const rolePermissions = res.data
        const menuIds: number[] = []
        const buttonIds: number[] = []
        const apiIds: number[] = []
        
        rolePermissions.forEach((permission: Permission) => {
          if (permission.type === 'MENU') {
            menuIds.push(permission.id)
          } else if (permission.type === 'BUTTON') {
            buttonIds.push(permission.id)
          } else if (permission.type === 'API') {
            apiIds.push(permission.id)
          }
        })
        
        checkedMenuKeys.value = menuIds
        checkedButtonKeys.value = buttonIds
        checkedApiKeys.value = apiIds
        
        // 设置表格选中状态
        await nextTick()
        if (buttonTableRef.value) {
          buttonPermissions.value.forEach((permission: Permission) => {
            if (buttonIds.includes(permission.id)) {
              buttonTableRef.value.toggleRowSelection(permission, true)
            }
          })
        }
        if (apiTableRef.value) {
          apiPermissions.value.forEach((permission: Permission) => {
            if (apiIds.includes(permission.id)) {
              apiTableRef.value.toggleRowSelection(permission, true)
            }
          })
        }
        
        console.log('角色权限加载完成:', {
          roleId: role.id,
          roleName: role.name,
          menuPermissions: checkedMenuKeys.value,
          buttonPermissions: checkedButtonKeys.value,
          apiPermissions: checkedApiKeys.value
        })
      }
    } catch (error) {
      ElMessage.error('获取角色权限失败')
    }
  }
}

const handleMenuCheckChange = (data: Permission, checked: boolean, indeterminate: boolean) => {
  if (checked) {
    if (!checkedMenuKeys.value.includes(data.id)) {
      checkedMenuKeys.value.push(data.id)
    }
  } else {
    const index = checkedMenuKeys.value.indexOf(data.id)
    if (index > -1) {
      checkedMenuKeys.value.splice(index, 1)
    }
  }
}

const handleButtonSelectionChange = (selection: Permission[]) => {
  checkedButtonKeys.value = selection.map(p => p.id)
}

const handleApiSelectionChange = (selection: Permission[]) => {
  checkedApiKeys.value = selection.map(p => p.id)
}

// 保存权限
const handleSavePermissions = async () => {
  if (!selectedRole.value) return
  
  saving.value = true
  try {
    // 收集所有选中的权限ID
    const allPermissionIds = [
      ...checkedMenuKeys.value,
      ...checkedButtonKeys.value,
      ...checkedApiKeys.value
    ]
    
    // 调用API更新角色权限
    const res = await userApi.updateRolePermissions(selectedRole.value.id, allPermissionIds)
    
    if (res && res.code === 200) {
      ElMessage.success('权限保存成功')
      // 更新当前角色的权限数量显示
      if (selectedRole.value) {
        selectedRole.value.permissions = allPermissionIds.map(id => ({
          id,
          type: 'MENU', // 这里只是用于显示数量，实际类型不重要
          name: '',
          code: '',
          enable: true,
          show: true
        }))
      }
      
      // 如果是超级管理员，提示刷新页面使权限生效
      if (selectedRole.value.code === 'SUPER_ADMIN') {
        ElMessage.info('超级管理员权限已保存，建议刷新页面使权限生效')
      }
    } else {
      ElMessage.error(res?.message || '权限保存失败')
    }
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('权限保存失败')
  } finally {
    saving.value = false
  }
}

// 重置权限
const handleResetPermissions = async () => {
  if (!selectedRole.value) return
  
  // 清空表格选中状态
  await nextTick()
  if (buttonTableRef.value) {
    buttonTableRef.value.clearSelection()
  }
  if (apiTableRef.value) {
    apiTableRef.value.clearSelection()
  }
  
  // 如果是超级管理员，重新选中所有权限
  if (selectedRole.value.code === 'SUPER_ADMIN') {
    const getAllMenuIds = (permissions: Permission[]): number[] => {
      let ids: number[] = []
      permissions.forEach(permission => {
        ids.push(permission.id)
        if (permission.children && permission.children.length > 0) {
          ids = ids.concat(getAllMenuIds(permission.children))
        }
      })
      return ids
    }
    
    checkedMenuKeys.value = getAllMenuIds(menuPermissionTree.value)
    checkedButtonKeys.value = buttonPermissions.value.map(p => p.id)
    checkedApiKeys.value = apiPermissions.value.map(p => p.id)
    
    // 设置表格选中状态
    await nextTick()
    if (buttonTableRef.value) {
      buttonPermissions.value.forEach((permission: Permission) => {
        buttonTableRef.value.toggleRowSelection(permission, true)
      })
    }
    if (apiTableRef.value) {
      apiPermissions.value.forEach((permission: Permission) => {
        apiTableRef.value.toggleRowSelection(permission, true)
      })
    }
    
    ElMessage.success('权限已重置为全部权限')
  } else {
    // 重新获取角色的实际权限
    try {
      const res = await userApi.getRolePermissions(selectedRole.value.id)
      if (res && res.code === 200 && res.data) {
        const rolePermissions = res.data
        
        // 重置权限选择
        checkedMenuKeys.value = []
        checkedButtonKeys.value = []
        checkedApiKeys.value = []
        
        const menuIds: number[] = []
        const buttonIds: number[] = []
        const apiIds: number[] = []
        
        rolePermissions.forEach((permission: Permission) => {
          if (permission.type === 'MENU') {
            menuIds.push(permission.id)
          } else if (permission.type === 'BUTTON') {
            buttonIds.push(permission.id)
          } else if (permission.type === 'API') {
            apiIds.push(permission.id)
          }
        })
        
        checkedMenuKeys.value = menuIds
        checkedButtonKeys.value = buttonIds
        checkedApiKeys.value = apiIds
        
        // 设置表格选中状态
        await nextTick()
        if (buttonTableRef.value) {
          buttonPermissions.value.forEach((permission: Permission) => {
            if (buttonIds.includes(permission.id)) {
              buttonTableRef.value.toggleRowSelection(permission, true)
            }
          })
        }
        if (apiTableRef.value) {
          apiPermissions.value.forEach((permission: Permission) => {
            if (apiIds.includes(permission.id)) {
              apiTableRef.value.toggleRowSelection(permission, true)
            }
          })
        }
        
        ElMessage.success('权限已重置')
      }
    } catch (error) {
      console.error('重置权限失败:', error)
      ElMessage.error('重置权限失败')
    }
  }
}

// 获取方法标签类型
const getMethodTagType = (method: string): string => {
  const methodMap: Record<string, string> = {
    'GET': 'success',
    'POST': 'primary',
    'PATCH': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 角色管理方法
const handleAddRole = () => {
  isRoleEdit.value = false
  currentRole.value = null
  roleDialogVisible.value = true
}

const handleEditRole = (role: Role) => {
  isRoleEdit.value = true
  currentRole.value = { ...role }
  roleDialogVisible.value = true
}

const handleDeleteRole = (role: Role) => {
  // 检查角色是否被用户使用（这里需要根据实际API返回的数据结构调整）
  // if (role.users && role.users.length > 0) {
  //   ElMessage.warning('该角色已被用户使用，无法删除')
  //   return
  // }

  ElMessageBox.confirm(
    `确定要删除角色 "${role.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await userApi.deleteRole(role.id)
      
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        fetchRoleList()
        // 如果删除的是当前选中的角色，清空选择
        if (selectedRole.value && selectedRole.value.id === role.id) {
          selectedRole.value = null
          checkedMenuKeys.value = []
          checkedButtonKeys.value = []
          checkedApiKeys.value = []
        }
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleRoleDialogSuccess = () => {
  roleDialogVisible.value = false
  fetchRoleList()
}

// 加载数据
onMounted(() => {
  fetchRoleList()
  fetchPermissionData()
})
</script>

<style scoped>
.role-permission-tab {
  padding: 0;
}

.role-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.permission-card {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.permission-assignment {
  padding: 0;
}

.admin-alert {
  margin-bottom: 20px;
}

.permission-tabs {
  margin-bottom: 20px;
}

.permission-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 10px;
}

.permission-tree {
  min-height: 200px;
}

.permission-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  color: var(--el-color-primary);
}

.node-label {
  font-weight: 500;
}

.path-tag {
  margin-left: 4px;
}

.button-permissions,
.api-permissions {
  max-height: 400px;
  overflow-y: auto;
}

.preview-card {
  margin-bottom: 20px;
}

.permission-preview {
  padding: 0;
}

.preview-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px 0;
}

.preview-tag {
  margin: 2px;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 6px 0;
}

:deep(.el-tree-node__expand-icon) {
  margin-right: 8px;
}
</style>
